import { logout } from '@/store/actions/login'
import { isAuth } from '@/utils/token'
import { useDispatch } from 'react-redux'
import { Route, RouteProps, Redirect, useLocation } from 'react-router-dom'
import { Dispatch } from 'redux'

export const AuthRoute = ({ children, ...rest }: RouteProps) => {
  const location = useLocation()
  const dispatch = useDispatch<Dispatch<any>>()
  return (
    <Route
      {...rest}
      render={() => {
        const isLogin = isAuth()

        if (isLogin) {
          return children as JSX.Element
        }

        dispatch(logout())
        return (
          <Redirect
            to={{
              pathname: '/login',
              state: {
                from: location.pathname,
              },
            }}
          ></Redirect>
        )
      }}
    ></Route>
  )
}
